<?php
namespace Tbf\Component\Process;
use Symfony\Component\Process\Process;

class ProcessFunction {
    /**
     * 运行某个process,保证一定成功,否则抛出异常
     * @param Process $process
     * @param null $cb
     * @throws \Exception
     * @return process
     */
    public static function mustSuccessRun(Process $process,$cb=null){
        $process->run($cb);
        if (!$process->isSuccessful()){
            throw new \Exception(sprintf('run process fail:%s',$process->getErrorOutput()));
        }
        return $process;
    }

    /**
     * 新建一个process,以便链式调用
     * @param $cmd_line
     * @param null $cwd
     * @param array $env
     * @param null $stdin
     * @param int $timeout
     * @param array $options
     * @return Process
     */
    public static function newProcess($cmd_line, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array()){
        return new Process($cmd_line,$cwd,$env,$stdin,$timeout,$options);
    }

    /**
     * 简单执行某个命令,返回output
     * 可以设置命令行和当前目录
     * 如果这个命令出错,抛出异常
     * @param $cmd_line
     * @param null $cwd
     */
    public static function runCmd($cmd_line,$cwd=null){
        $process = new Process($cmd_line,$cwd);
        $process->run();
        if (!$process->isSuccessful()){
            throw new \Exception(sprintf('run process fail:%s',$process->getErrorOutput()));
        }
        return $process->getOutput();
    }
}